﻿using System;
using System.Collections.Generic;
using System.Data;
using Garlic.CC.BaseClass;
using BLL.SystemManagement;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;

using DevExpress.Web.ASPxClasses;

namespace Garlic.BasicInfo
{
    public partial class FlightsVessels : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            Session["mainPage"] = Request.Url; //记住当前主页面地址，防止F5

            hidUserId.Value = CurrentUser.UserID.ToString();
            hidUserType.Value = CurrentUser.UserType.ToString();

            ServiceRouteTree1.iuser = CurrentUser; //当前用户
        }





        #region  event

        //根据服务航线获取班期
        protected void btnFlt_schdul_Click(object sender, EventArgs e)
        {
            string serviceLineID = ServiceRouteTree1.ServiceRouteID.ToString();



            DataTable shipAgent = FlightInfoBLL.GetShipAgency(CurrentUser.UserID);
            int? agentID = Int32.Parse(shipAgent.Rows[0]["cst_id"].ToString());
            if (CurrentUser.UserType == "1")
                agentID = null;

            if (!string.IsNullOrEmpty(serviceLineID))
            {
                DataTable flt_schdul = FlightInfoBLL.GetFlightScheduleBySln(agentID, serviceLineID);
                ddlFlt_schdul.DataTextField = "FLT_SCHDUL";
                ddlFlt_schdul.DataValueField = "FLT_ID";
                ddlFlt_schdul.DataSource = flt_schdul;
                ddlFlt_schdul.DataBind();
            }
            else
            {
                ddlFlt_schdul.Items.Clear();
            }
        }


        //根据条件查询出结果
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            GetLinersTable();
        }



        protected void btnAdd_Click(object sender, EventArgs e)
        {

        }

        protected void gridst_liners_PageIndexChanged(object sender, EventArgs e)
        {
            GetLinersTable();
        }

        protected void gridst_liners_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            int lnr_id = Convert.ToInt32(e.Keys[0]);
            int n = VesselsBLL.Delete_st_liners(lnr_id);
            e.Cancel = true;
            gridst_liners.CancelEdit();
            GetLinersTable();
        }

        protected void gridst_liners_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
        {

            if (!gridst_liners.IsEditing)
                return;

            ASPxComboBox combo = e.Editor as ASPxComboBox;
            //  if (combo == null) return;


            //航线1
            if (gridst_liners.IsEditing && e.Column.FieldName == "SRT_RTCHNNM")
            {
                Fill_srt_rtchnnmCombo(combo, CurrentUser);
            }


            //航线2
            if (e.Column.FieldName == "SLN_NAME")
            {
                ASPxComboBox cmbSlnName = e.Editor as ASPxComboBox;
                cmbSlnName.Callback += new CallbackEventHandlerBase(cmbSlnName_Callback);

                if (e.KeyValue == DBNull.Value || e.KeyValue == null) return;
                object val = gridst_liners.GetRowValuesByKeyValue(e.KeyValue, "SRT_RTCHNNM");
                if (val == DBNull.Value || val == null) return;
                string srt_rtchnnm = (string)val;

                Fill_flt_sln_rtchnnmCombo(combo, srt_rtchnnm, CurrentUser);
            }
            //班期
            if (e.Column.FieldName == "FLT_SCHDUL")
            {
                ASPxComboBox cmbScheduel = e.Editor as ASPxComboBox;
                cmbScheduel.Callback += new CallbackEventHandlerBase(cmbScheduel_Callback);
                if (gridst_liners.IsNewRowEditing)
                {
                    return;
                }
                object val = gridst_liners.GetRowValuesByKeyValue(e.KeyValue, "SLN_ID");

                if (val == DBNull.Value || val == null) return;
                string sln_ID = val.ToString();

                FillEditSchudule(cmbScheduel, sln_ID);
            }
            if (gridst_liners.IsEditing && e.Column.FieldName == "LNR_VSL_ID")
            {
                Fill_VesselsCombo(combo);
            }
            //船的英文名称
            if (e.Column.FieldName == "NAME")
            {
                FillComboVSL_CD(combo);
            }

            if (e.Column.FieldName == "VSL_CNNAME")
            {
                ASPxTextBox o = e.Editor as ASPxTextBox;
            }
        }


        //班期回调
        void cmbScheduel_Callback(object sender, CallbackEventArgsBase e)
        {
            FillEditSchudule(sender as ASPxComboBox, e.Parameter);
        }

        //服务航线2回调
        void cmbSlnName_Callback(object sender, CallbackEventArgsBase e)
        {
            FlightsVessels.Fill_flt_sln_rtchnnmCombo1(sender as ASPxComboBox, e.Parameter, CurrentUser);
        }

        #endregion





        #region private methods

        //填充航班船的英文名称（英文名家船舶代码）
        private void FillComboVSL_CD(ASPxComboBox cmb)
        {
            int? agentID = GetAgentIDByCustomerID();
            DataTable dt = VesselsBLL.GetVesselsByCompany(agentID == null ? null : agentID.ToString());
            cmb.DataSource = dt;
            cmb.ValueField = "IDCNName";
            cmb.TextField = "name";
            cmb.DataBind();
        }

        private void GetLinersTable()
        {

            int? pass_flt_id = null;
            int flt_id;

            bool check = Int32.TryParse(ddlFlt_schdul.SelectedValue, out flt_id);

            if (check)
                pass_flt_id = flt_id;


            gridst_liners.DataSource = VesselsBLL.GetLinersByFLT_ID(pass_flt_id, GetAgentIDByCustomerID());
            gridst_liners.DataBind();

        }

        //选中服务航线的时候填充航班班期
        private void FillEditSchudule(ASPxComboBox scheduleComb, string sln_ID)
        {
            int? agentID = GetAgentIDByCustomerID();
            DataTable dt = FlightInfoBLL.GetFlightScheduleBySln(agentID, sln_ID);

            scheduleComb.DataSource = dt;
            scheduleComb.ValueField = "FLT_ID";
            scheduleComb.TextField = "ScheduleNo";
            scheduleComb.DataBind();

        }

        private int? GetAgentIDByCustomerID()
        {
            DataTable shipAgent = FlightInfoBLL.GetShipAgency(CurrentUser.UserID);
            int? agentID = Int32.Parse(shipAgent.Rows[0]["cst_id"].ToString());
            if (CurrentUser.UserType == "1")
                agentID = null;
            return agentID;
        }

        #endregion




        void AddError(Dictionary<GridViewColumn, string> errors, GridViewColumn column, string errorText)
        {
            if (errors.ContainsKey(column)) return;
            errors[column] = errorText;
        }



        public static void Fill_srt_rtchnnmCombo(ASPxComboBox cmb, IUser user)
        {
            if (cmb == null) return;
            cmb.Items.Clear();
            DataTable dt = ServiceRouteTreeBLL.GetRoutes1(user.UserID, user.UserType);
            foreach (DataRow item in dt.Rows)
            {
                cmb.Items.Add(new ListEditItem(item["SRT_RTCHNNM"].ToString(), item["SRT_ID"].ToString()));
            }
        }


        public static void Fill_flt_sln_rtchnnmCombo1(ASPxComboBox cmb, string flt_sln_id, IUser user)
        {
            if (flt_sln_id == "") return;
            cmb.Items.Clear();
            DataTable dt = ServiceRouteTreeBLL.GetRoutes2(user.UserID, user.UserType, int.Parse(flt_sln_id));

            foreach (DataRow row in dt.Rows)
            {

                cmb.Items.Add(new ListEditItem(row["sln_name"].ToString(), row["sln_id"].ToString()));
            }
        }




        /// <summary>
        /// 根据一级航线填充二级航线，并且选中值
        /// </summary>
        /// <param name="cmb"></param>
        /// <param name="srt_rtchnnm"></param>
        /// <param name="user"></param>
        public static void Fill_flt_sln_rtchnnmCombo(ASPxComboBox cmb, string srt_rtchnnm, IUser user)
        {
            if (srt_rtchnnm == "") return;
            cmb.Items.Clear();
            DataTable dt = ServiceRouteTreeBLL.GetRoutes2(user.UserID, user.UserType, ServiceRouteTreeBLL.GetSt_sea_routesBysrt_id(srt_rtchnnm));
            foreach (DataRow row in dt.Rows)
            {
                cmb.Items.Add(new ListEditItem(row["sln_name"].ToString(), row["sln_id"].ToString()));
            }
        }

        protected void Fill_VesselsCombo(ASPxComboBox cmb)
        {
            if (cmb == null) return;
            cmb.Items.Clear();

            DataTable vesselstable = VesselsBLL.GetAllVessels();
            foreach (DataRow row in vesselstable.Rows)
            {
                cmb.Items.Add(new ListEditItem(row["vsname"].ToString(), row["vsl_id"].ToString()));
            }

        }



        void OnCallback(object source, CallbackEventArgsBase e)
        {
            Fill_flt_sln_rtchnnmCombo1(source as ASPxComboBox, e.Parameter, CurrentUser);
        }


        protected void gridst_liners_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e)
        {
            //Match m = Regex.Match(e.NewValues["lnr_istep"].ToString(), "[0-9]{1,20}");
            //if (!m.Success)
            //{
            //    AddError(e.Errors, gridst_liners.Columns["lnr_istep"], "无效的");
            //}
        }

        protected void gridst_liners_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            // #Update DB
            int n = VesselsBLL.Update_st_liners(Convert.ToInt32(e.Keys[0]),
                Convert.ToString(e.NewValues["LNR_IVOYAGE"]), Convert.ToString(e.NewValues["LNR_EVOYAGE"]),
                Convert.ToString(e.NewValues["LNR_ISTEP"]), Convert.ToString(e.NewValues["LNR_IAMOUNT"]),
                Convert.ToString(e.NewValues["LNR_EAMOUNT"]), Convert.ToString(e.NewValues["LNR_ESTEP"]),
                CurrentUser.AccountName);
            e.Cancel = true;
            gridst_liners.CancelEdit();
            GetLinersTable();
        }

        protected void gridst_liners_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            //TODO:获取航班ID
            int LNR_FLT_ID = Int32.Parse(hiddenST_FL_ID.Value);
            char[] chars = new char[] { '+' };
            string LNR_VSL_CD = e.NewValues["NAME"].ToString().Split(chars)[1];
            string strLNR_ISTEP = e.NewValues["LNR_ISTEP"].ToString();
            int? LNR_ISTEP = null;
            if (!string.IsNullOrEmpty(strLNR_ISTEP))
            {
                LNR_ISTEP = Int32.Parse(strLNR_ISTEP);
            }

            string strLNR_ESTEP = e.NewValues["LNR_ESTEP"].ToString();
            int? LNR_ESTEP = null;
            if (!string.IsNullOrEmpty(strLNR_ESTEP))
            {
                LNR_ISTEP = Int32.Parse(strLNR_ESTEP);
            }

            string LNR_IVOYAGE = e.NewValues["LNR_IVOYAGE"].ToString();
            string LNR_EVOYAGE = e.NewValues["LNR_EVOYAGE"].ToString();

            string strLNR_VSL_ID = hiddenLNR_VSL_ID.Value;

            int LNR_VSL_ID = Int32.Parse(strLNR_VSL_ID);



            string strLNR_IAMOUNT = e.NewValues["LNR_IAMOUNT"].ToString();
            int? LNR_IAMOUNT = null;
            if (!string.IsNullOrEmpty(strLNR_IAMOUNT))
            {
                LNR_ISTEP = Int32.Parse(strLNR_IAMOUNT);
            }


            string strLNR_EAMOUNT = e.NewValues["LNR_EAMOUNT"].ToString();
            int? LNR_EAMOUNT = null;
            if (!string.IsNullOrEmpty(strLNR_EAMOUNT))
            {
                LNR_ISTEP = Int32.Parse(strLNR_EAMOUNT);
            }


            VesselsBLL.InsertLiners(LNR_VSL_CD, LNR_FLT_ID, LNR_ISTEP, LNR_ESTEP, LNR_IVOYAGE, LNR_EVOYAGE,
               CurrentUser.AccountName, LNR_VSL_ID, LNR_IAMOUNT, LNR_EAMOUNT);
            e.Cancel = true;
            gridst_liners.CancelEdit();
            GetLinersTable();
        }



    }
}